<template>
  <div>
    <div>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="4" :sm="24">
                     <a-form-model-item
                :label="$t('all.autotext1693')"
                labelAlign="left"
              >
              <a-select v-model="queryParam.read" allowClear @change="changeReadStatus">
                  <a-select-option :value="-1" >
                    {{ $t('all.autotext600') }}
                  </a-select-option>
                  <a-select-option :value="0" >
                    {{ $t('all.autotext478') }}
                  </a-select-option>
                  <a-select-option :value="1" >
                    {{  $t('all.autotext584')  }}
                  </a-select-option>
                </a-select>
              </a-form-model-item> 
            </a-col> 
     
            <a-col :md="6" :sm="24">

              <a-form-model-item
                :label="$t('all.autotext666')"
                labelAlign="left"
              >
                <a-range-picker
                  v-model="timeValue"
                  valueFormat="YYYY-MM-DD"
                  @change="handleChangeDate"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-model-item
                :label="$t('all.autotext1692')"
                labelAlign="left"
              >
                <a-input v-model="queryParam.applyNo" />
              </a-form-model-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-model-item
                :label="$t('all.autotext992')"
                labelAlign="left"
              >
                <a-input v-model="queryParam.proNo" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-space>
                <a-button type="primary" @click="initLoadData">{{
                  $t('all.autotext30')
                }}</a-button>
                <a-button style="margin-left: 8px" @click="clearCondition">{{
                  $t('all.autotext340')
                }}</a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table">
        <s-table
          ref="table"
          size="default"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ x: 1000 }"
        >
          <span slot="operation" slot-scope="text, record">
            <a-badge
              :dot="record.boolRead !== 1"
              v-if="
                !record.deleteProjectFlag &&
                record.todoType !== 3 &&
                record.todoType !== 5 &&
                record.todoType !== 2 &&
                record.todoType !== 9
              "
            >
              <a @click="clickDetail(record)">{{ $t('all.autotext568') }}</a>
            </a-badge>
          </span>
          <span
            class="content-title"
            slot="contentTitle"
            slot-scope="text"
            :title="text"
          >
            {{ text }}
          </span>
          <span slot="createTime" slot-scope="text, record">{{
            record.createTime | moment
          }}</span>
          <span slot="boolRead" slot-scope="text">{{
            text ? $t('all.autotext584') : $t('all.autotext478')
          }}</span>
        </s-table>
      </div>

      <MessageDetailModal
        :visible="messageVisible"
        :content="messageContent"
        @cancel="handleMessageDetailCancel"
      ></MessageDetailModal>

      <ViewCenterMemberModal
        ref="viewCenterMemberRef"
        :mProId="projectId"
        :viewCenterModalVisible="viewCenterModalVisible"
        :viewCenterMemberDetail="viewCenterMemberDetail"
        :hospitalNameProp="hospitalNameProp"
        @closeViewCenterModal="handleResearchMsgCancel"
      />
      <DetailView
        @refresh="$refs.table.refresh()"
        @closeCallback="closeCallback"
        @openPopup="openPopup"
        @payRecord="handlePayRecord"
        ref="detailView"
        :visible="feeVisible"
        :costId="costId"
      />
      <AuditFailure
        :visible="visibles"
        @uploadModalCancel="visibles = false"
        @uploadClickConfirm="uploadClickConfirm"
        :auditStatus="auditStatus"
        ref="AuditFailure"
      />
      <Approve
        v-model="oveVisibles"
        :auditStatus="auditStatus"
        @ok="approveOk"
      />
      <ViewModal
        :visible="viewVisible"
        :mProId="projectId"
        @close="viewVisible = false"
        @closeViewModal="refreshTable"
        :uId="ptsId"
        :isEdit="false"
        ref="viewModalRef"
      />
      <!-- 预算调整弹窗 -->
      <ViewBudget
        ref="budgetRef"
        :is-audit="false"
        :viewType="viewType"
        handType="view"
      />
      <!-- 意见反馈弹窗 -->
      <feedModal
        v-if="showFeedDetailModal"
        ref="feedRef"
        @close="showFeedDetailModal = false"
      />
      <feedCenterModal
        v-if="showFeedcenterModal"
        ref="feedCenterRef"
        @close="showFeedcenterModal = false"
      />
      <!-- 入账管理 -->
      <examineModal ref="examineRef" />
    </div>
  </div>
</template>
<script>
import {
  getMessageList,
  updateMessage,
  getUnread,
  isProjectPm,
  apiRecordViewMsg,
  checkUserForProOrSysUser
} from '@/api/system/message'
import MessageDetailModal from './MessageDetailModal.vue'
import ViewCenterMemberModal from '../../overview/detail/responsible/components/members/ViewCenterMemberModal.vue'
import DetailView from '@/views/cost-auditing/detail.vue'
import AuditFailure from '@/views/cost-auditing/components/auditFailure'
import Approve from '@/views/cost-auditing/components/approve'
import {
  costRecordPay,
  switchAudit,
  preCheckForFinanceAudit
} from '@/api/cost/audit'
import ViewBudget from '@views/overview/detail/treasurer/components/budget/viewBudget'
import feedModal from '@views/feedback/components/feedModal'
import feedCenterModal from '@views/feedcenter/components/feedModal'
import ViewModal from '../../overview/detail/responsible/components/subject/viewModal.vue' // 查看页面
import examineModal from '@views/entry/components/examineModal'
// import { getResearchDetail } from '@/api/overview/member'
import { uploadLog } from '@/utils/log'
import { mapActions } from 'vuex'
export default {
  components: {
    MessageDetailModal,
    ViewCenterMemberModal,
    DetailView,
    AuditFailure,
    Approve,
    ViewModal,
    ViewBudget,
    feedModal,
    feedCenterModal,
    examineModal
  },
  props: {
    type: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      applyNo: '',
      oldStatus: '',
      researchDetailId: '',
      viewVisible: false,
      projectId: '',
      ptsId: '',
      timeValue: null,
      // tab切换时，更改queryParams中的状态字段。
      queryParam: {
        proId: this.$route.query.form
          ? ''
          : localStorage.getItem('CURRENT_PROID'),
        auditStatus: this.type,
        systemId: this.$const.SYSTEM_TYPE.PAYMENT.value,
        read:-1,
      },
      advanced: false,
      columns: [
        {
          title: this.$t('all.autotext992'),
          dataIndex: 'proNo'
        },
        {
          title: this.$t('all.autotext1692'),
          dataIndex: 'applyNo'
        },
        {
          title: this.$t('all.autotext818'),
          dataIndex: 'title',
          width: '300px',
          scopedSlots: { customRender: 'contentTitle' }
        },
        {
          title: this.$t('all.autotext666'),
          dataIndex: 'createTime',
          minWidth: '200px',
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: this.$t('all.autotext1693'),
          dataIndex: 'boolRead',
          minWidth: '100px',
          scopedSlots: { customRender: 'boolRead' }
        },
        {
          title: this.$t('all.autotext187'),
          dataIndex: 'operation',
          width: '70px',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const params = {...this.queryParam}
        params.read == - 1 &&  delete params.read
        this.getNoReadCounts({})
        return getMessageList(Object.assign(parameter, params)).then(
          (res) => {
            return res
          }
        )
      },
      // 有数据之后下边要删掉
      dataTable: [],
      // 消息详情查看弹窗 显示/隐藏
      messageVisible: false,
      // 消息详情内容
      messageContent: '',
      // 研究者 邀请信息弹窗
      viewCenterModalVisible: false,
      viewCenterMemberDetail: {},
      hospitalNameProp: null,
      // 费用审批弹窗
      feeVisible: false,
      costId: null,
      // 审核弹窗
      oveVisibles: false,
      visibles: false,
      auditStatus: {},
      readList: [
        {
          label: this.$t('all.autotext600'),
          value: ''
        },
        {
          label: this.$t('all.autotext478'),
          value: 0
        },
        {
          label: this.$t('all.autotext584'),
          value: 1
        }
      ],
      costList: [
        {
          label: this.$t('all.autotext600'),
          value: ''
        },
        {
          label: this.$const.EXAMINE_TYPE.WAITCOMMIT.desc,
          value: this.$const.EXAMINE_TYPE.WAITCOMMIT.value
        },
        {
          label: this.$const.EXAMINE_TYPE.WAITPROOF.desc,
          value: this.$const.EXAMINE_TYPE.WAITPROOF.value
        },
        {
          label: this.$const.EXAMINE_TYPE.WAITAPPROVE.desc,
          value: this.$const.EXAMINE_TYPE.WAITAPPROVE.value
        },
        {
          label: this.$const.EXAMINE_TYPE.CHECKING.desc,
          value: this.$const.EXAMINE_TYPE.CHECKING.value
        },
        {
          label: this.$const.EXAMINE_TYPE.REFUSE.desc,
          value: this.$const.EXAMINE_TYPE.REFUSE.value
        },
        {
          label: this.$const.EXAMINE_TYPE.DAIZHIFU.desc,
          value: this.$const.EXAMINE_TYPE.DAIZHIFU.value
        },
        {
          label: this.$const.EXAMINE_TYPE.PAYINT.desc,
          value: this.$const.EXAMINE_TYPE.PAYINT.value
        },
        {
          label: this.$const.EXAMINE_TYPE.YIWANCHENG.desc,
          value: this.$const.EXAMINE_TYPE.YIWANCHENG.value
        }
      ],
      auditList: [
        {
          label: this.$t('all.autotext600'),
          value: ''
        },
        {
          label: this.$const.APPROVAL_STATUS.WAIT.desc,
          value: this.$const.APPROVAL_STATUS.WAIT.value
        },
        {
          label: this.$const.APPROVAL_STATUS.ADOPT.desc,
          value: this.$const.APPROVAL_STATUS.ADOPT.value
        },
        {
          label: this.$const.APPROVAL_STATUS.NO_APPROVAL.desc,
          value: this.$const.APPROVAL_STATUS.NO_APPROVAL.value
        },
        {
          label: this.$const.APPROVAL_STATUS.APPROVAL.desc,
          value: this.$const.APPROVAL_STATUS.APPROVAL.value
        },
        {
          label: this.$const.APPROVAL_STATUS.REJECT.desc,
          value: this.$const.APPROVAL_STATUS.REJECT.value
        },
        {
          label: this.$const.APPROVAL_STATUS.NO_PAY.desc,
          value: this.$const.APPROVAL_STATUS.NO_PAY.value
        },
        {
          label: this.$const.APPROVAL_STATUS.COMPLETED.desc,
          value: this.$const.APPROVAL_STATUS.COMPLETED.value
        }
      ],
      showFeedcenterModal: false,
      showFeedDetailModal: false,
      viewType: ''
    }
  },
  methods: {
    ...mapActions(['getNoReadCounts']),
    approveOk() {
      this.visibles = false
      this.visible = false
    },
    // 清除条件
    clearCondition() {
      this.queryParam = {
        ptsNo: '',
        systemId: this.$const.SYSTEM_TYPE.PAYMENT.value
      }
      this.timeValue = null
      this.$refs.table.refresh(true)
    },
    // 时间选择器 回调
    handleChangeDate(e) {
      this.queryParam.startTime = e[0]
      this.queryParam.endTime = e[1]
    },
    // 更新消息状态 已读
    updateMessageReaded(record) {
      updateMessage({
        id: record.id,
        boolRead: 1
      }).then((res) => {
        this.$refs.table.refresh()
        getUnread({ proId: localStorage.getItem('CURRENT_PROID') }).then(
          (res) => {
            this.$globalVue.$emit('unReadMsgCount', res)
          }
        )
      })
    },
    isNotVersionUpdateMessage({ projectId }) {
      // 后端协商 用是否有项目id来判断是不是版本升级的消息，目前只有版本升级的消息没有项目id
      return projectId
    },
    initLoadData(){
      this.$refs.table.refresh(true)
      this.getNoReadCounts({})
    },
    changeReadStatus() {
      this.initLoadData()
    },
    // 查看详情
    async clickDetail(record) {
      if (record.boolRead === 0) {
        this.updateMessageReaded(record)
      }

      if (this.isNotVersionUpdateMessage(record) && record.todoType !== 4) {
        const res = await isProjectPm({ proId: record.projectId })
        if (!res && !this.isVersionUpdateMessage(record))
          return this.$message.warning(this.$t('all.autotext1512'))
      }
      this.getNoReadCounts({})

      // if (record.channelType === this.$const.MESSAGE_TYPE.SYSTEM.value) {
      //   this.messageContent = record.content
      //   this.messageVisible = true
      // } else {
      //   if (record.todoType === 1) {
      //     this.$router.push(`/system/feedcenter?from=message&id=${record.todoId}`)
      //     return
      //   } else if (record.costId) {
      //     // 如果是费用审核
      //     this.costId = record.costId
      //     this.feeVisible = true
      //   } else if (record.ptsId) {
      //     // 如果是受试者
      //     this.ptsId = record.ptsId
      //     this.projectId = record.projectId
      //     this.viewVisible = true
      //   } else if (record.researchDetailId) {
      //     this.researchDetailId = record.researchDetailId
      //     this.projectId = record.projectId
      //     getResearchDetail({ detailId: this.researchDetailId }).then(res => {
      //       this.viewCenterMemberDetail = res.detail
      //       this.hospitalNameProp = res.orgName
      //       this.viewCenterModalVisible = true
      //     })
      //   }
      // }

      if (record.todoType === 1) {
        // 意见反馈
        if (this.$store.getters.userInfo.isAdmin === 1) {
          this.showFeedcenterModal = true
          this.$nextTick(() => this.$refs.feedCenterRef.open(record.todoId))
        } else {
          this.showFeedDetailModal = true
          this.$nextTick(() => this.$refs.feedRef.open(record.todoId))
        }
      } else if (record.todoType === 2) {
        if (record.budgetFlag === 1) {
          // 如果是新增预算
          this.viewType = 'addBudget'
        } else {
          // 如果是预算调整
          this.viewType = 'adjustBudget'
        }
        this.$refs.budgetRef.open(record.todoId, record.projectId)
      } else if (record.todoType === 4) {
        const res = await checkUserForProOrSysUser({ proId: record.projectId })
        if (!res) {
          this.$message.warning(this.$t('all.autotext1713'))
          return
        }
        // 如果是项目通知
        this.$store.dispatch('EnterProject', record.proInfo).then((e) => {
          this.$router.push({ name: 'Responsible' })
        })
      } else if (record.todoType === 5) {
        // 如果是待补充资料
        this.$router.push({
          name: 'RecordDetail',
          query: {
            id: record.todoId
          }
        })
      } else if (record.todoType === 6) {
        // 如果是入账审批
        this.$refs.examineRef.open(record.todoId, 2)
      } else if (record.todoType === 8) {
        // 如果是项目预算预警
        this.$store.dispatch('EnterProject', record.proInfo).then((e) => {
          this.$router.push({ name: 'Responsible' })
        })
      } else if (record.todoType === 3 || record.costId) {
        if (record.refuseOrRevokeFlag) {
          this.$store.dispatch('EnterProject', record.proInfo).then((e) => {
            this.$router.push({
              name: 'ApplyDetail',
              query: {
                id: record.costId,
                status: record.costStatus
              }
            })
          })
          return
        }
        // 如果是费用审核
        this.costId = record.costId
        this.feeVisible = true
      } else {
        this.messageContent = record.content
        this.messageVisible = true
      }

      this.uploadViewLog(record)
    },
    uploadViewLog({ id }) {
      uploadLog(apiRecordViewMsg, {
        id
      })
    },
    // 消息详情 关闭 回调
    handleMessageDetailCancel() {
      this.messageVisible = false
    },
    handleResearchMsgCancel() {
      this.viewCenterModalVisible = false
      this.$refs.table.refresh(true)
    },
    // 打开审核弹窗
    async openPopup(value) {
      if (value.status === 1) {
        this.auditStatus = value
        this.oveVisibles = true
        return
      }
      if (
        value.status === true &&
        this.$store.getters.roles[0]?.code === 'SYS_FINANCE'
      ) {
        const check = await preCheckForFinanceAudit({ feeApplyId: value.id })
        if (check.flag) {
          const that = this
          this.$confirm({
            title: this.$t('all.autotext730'),
            content: (h) => {
              return h(
                'div',
                check.message.map((node) => h('p', node))
              )
            },
            onOk() {
              that.handleSure(value)
            }
          })
        } else {
          this.handleSure(value)
        }
        return
      }
      this.handleSure(value)
    },
    handleSure(value) {
      this.applyNo = value.applyNo
      this.oldStatus = value.oldStatus
      this.auditStatus = value
      this.visibles = true
    },
    // 弹窗关闭回调
    closeCallback() {
      this.feeVisible = false
    },
    // 支付记录回调
    handlePayRecord() {
      this.$refs.detailView.payLoading = true
      costRecordPay({ id: this.costId, applyNo: this.applyNo })
        .then((res) => {
          this.$refs.detailView.payLoading = false
          this.$message.success(this.$t('all.autotext470'))
          this.closeCallback()
          this.uploadModalCancel()
        })
        .catch((_) => {
          this.$refs.detailView.payLoading = false
        })
    },
    // 审核弹窗关闭回调
    uploadModalCancel() {
      this.visibles = false
      this.oveVisibles = false
    },
    // 审核弹窗确认回调
    uploadClickConfirm(value) {
      const status = value.status === true ? 1 : -1
      this.$refs.AuditFailure.confirmLoading = true
      switchAudit({
        id: value.id,
        status: status,
        applyNo: this.applyNo,
        oldStatus: this.oldStatus,
        refuseReason: value.refuseReason,
        comment: value.comment,
        auditArray: value.auditArray.length
          ? JSON.stringify(value.auditArray)
          : undefined
      })
        .then((res) => {
          this.$refs.table.refresh()
          this.$refs.AuditFailure.confirmLoading = false
          this.$refs.AuditFailure.form = {}
          this.$message.success(this.$t('all.autotext470'))
          this.closeCallback()
          this.uploadModalCancel()
        })
        .catch(() => {
          this.$refs.AuditFailure.confirmLoading = false
        })
    },
    refreshTable() {
      this.viewVisible = false
      this.$refs.table.refresh(true)
    }
  }
}
</script>
<style scoped lang="less">
.table {
  /deep/ .table-wrapper {
    .ant-table {
      td {
        white-space: nowrap;
        .content-title {
          display: inline-block;
          max-width: 250px;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
}
</style>
